#include "StdAfx.h"
#include <math.h>
#include "generic_math.h"

uint32_t invert_opt(uint32_t b)
{    
    return ((b * 0x0802LU & 0x22110LU) | (b * 0x8020LU & 0x88440LU)) * 0x10101LU >> 16;
}

uint32_t invert_bits(uint32_t number)
{
    //inverte os bits de um inteiro
    //exemplo: 11010 vira 01011
    //1111001 vira 1001111     
    //clz number
    uint32_t n = number;
    uint32_t i = 0x0;    
    uint32_t mask=0xFFFFFFFF;

    while(n){        
        n &= mask;        
        mask &= ~(0x1<<i); 
        i++;
    }
    if(i){
        i--;
    }
    uint32_t resp = 0;
    uint32_t bits = i;
    for(uint32_t j=0;j<32;j++)
    {
        if(number&(0x1<<(31-j)))
            resp |= (0x1<<j);
    }
    return resp>>(32-i);
}

/*
bool* int2boolvec(uint32_t number, uint32_t &size)
{
    size = (uint32_t)log((float)number) / log(2.);
    if(pow(2,size) < number){
        size++;
    }
    bool* resp = new bool[size];
    for(uint32_t i=0;i<size;i++)
    {
        resp[i] = number & 0x1<<i;
    }
    return resp;
}*/

void xor(bool* a, bool* b, bool* resp, uint32_t size)
{
    for(uint32_t i=0;i<size;i++)
    {
        resp[i] = ((a[i] || b[i]) && !(a[i] && b[i]));
    }
}

bool xor(bool a, bool b)
{
       return (a || b) && !(a && b);
}

bool vector_xor(uint32_t v)
{
    //true if the number of bit ones of number is odd
    //false otherwise
    uint32_t c; // c accumulates the total bits set in v
    for (c = 0; v; c++)
    {
        v &= v - 1; // clear the least significant bit set
    }
    return (c%2==1);
}